"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
const fs = __importStar(require("fs"));
const path_1 = __importDefault(require("path"));
const vue_1 = require("vue");
const import_file_1 = __importDefault(require("../../OtherCompoents/import_file/import_file"));
const lib_css_1 = __importDefault(require("../../../../../../@libs/nodejs-lib-main/lib_css"));
const XLSX = __importStar(require("xlsx"));
const util_1 = __importDefault(require("util")); // 添加这行导入
const icons_vue_1 = require("@element-plus/icons-vue");
const element_plus_1 = require("element-plus");
const signList = new Map([
    ["对话", '#'],
    ["对话流", '#'],
    ["选择", '&'],
    ["战斗", '@'],
    ["结束", 'END'],
]);
let allRewardData = [];
const component = {
    name: 'control_panel',
    props: {
        userData: Object || String,
        lf: Object || String,
        catTurboData: Boolean,
    },
    template: fs.readFileSync(`${__dirname}/control_panel.html`, "utf-8"),
    components: { ImportFile: import_file_1.default, CircleCloseFilled: icons_vue_1.CircleCloseFilled },
    methods: {
        $_zoomIn() {
            this.$props.lf.zoom(true);
        },
        $_zoomOut() {
            this.$props.lf.zoom(false);
        },
        $_zoomReset() {
            this.$props.lf.resetZoom();
        },
        $_translateRest() {
            this.$props.lf.resetTranslate();
        },
        $_reset() {
            this.$props.lf.resetZoom();
            this.$props.lf.resetTranslate();
        },
        $_undo() {
            this.$props.lf.undo();
        },
        $_redo() {
            this.$props.lf.redo();
        },
        $_download() {
            this.$props.lf.getSnapshot();
        },
        $_catData() {
            this.$emit('catData');
        },
        $_uploadData() {
            let url = this.handleFileChange();
            this.$emit('uploadData', url);
        },
        $_exportData() {
            let url = this.handleFileChange();
            this.exportToExcel(url);
        },
        $_playDemo() {
            this.$emit('playDemo', this.$data.selectElement);
        },
        $_downloadData() {
            this.$emit('downloadData');
        },
        handleFileChange(event) {
            const element = this.$refs.fileInput;
            if (element && element.value && !element.value.startsWith("project://")) {
                return element.value;
            }
        },
        save(type) {
            return __awaiter(this, void 0, void 0, function* () {
                const config = {};
                switch (type) {
                    case 'root':
                        config.path = __dirname;
                        break;
                }
                const data = yield Editor.Dialog.save(config);
                if (!data.canceled) {
                    this.$emit("saveUserData");
                    this.savePath = data.filePath;
                }
            });
        },
        saveReward(reward) {
            const rewardData = [
                ["奖励名称", "奖励id", "奖励描述", "奖励初始值"],
                ["reward_name", "reward_id", 'reward_desc', 'reward_value'],
            ];
            reward.forEach(element => {
                const values = Object.values(element);
                rewardData.push(values);
            });
            return rewardData;
        },
        saveRole(role) {
            const roleData = [
                ["角色名称", "角色id", "角色图片地址", "角色描述", "角色其他属性"],
                ["role_name", "role_id", 'role_picUrl', 'role_desc', 'role_others'],
            ];
            role.forEach(element => {
                const values = [element.role_name, element.role_id, element.role_picUrl, element.role_desc, element.role_others];
                roleData.push(values);
            });
            return roleData;
        },
        saveLocation(location) {
            const locationData = [
                ["地点名称", "地点id", "地点图片地址", "地点描述", "地点其他属性"],
                ["location_name", "location_id", 'location_picUrl', 'location_desc', 'location_others'],
            ];
            location.forEach(element => {
                const values = [element.location_name, element.location_id, element.location_picUrl, element.locationdesc, element.location_others];
                locationData.push(values);
            });
            return locationData;
        },
        savePlotCraft(graph, allReward) {
            let graphData = [
                ['标志', '父ID', '子ID', '人物', '人物ID', '位置', '对话内容', '背景图片', '跳转', '失败跳转'],
                ['sign', 'parent_id', 'id', 'role', 'roleID', 'boxPos', 'content', 'backPic', 'skip', 'failSkip']
            ];
            console.log("allReward", allReward);
            const allReward_Name = allReward.map(reward => reward.reward_name);
            const allReward_Id = allReward.map(reward => reward.reward_id);
            graphData = [graphData[0].concat(allReward_Name),
                graphData[1].concat(allReward_Id)
            ];
            console.log("graphData", graphData);
            const startNode = graph.filter(item => item.properties.graphRes_type === '开始');
            console.log("startNode", startNode);
            if (startNode.length > 0) {
                const parentID = startNode[0].properties.startID;
                const nextNode = this.$props.lf.getNodeOutgoingNode(startNode[0].id);
                if (nextNode) {
                    graphData = this.saveNextNode(graphData, nextNode, parentID);
                    console.log("graphData", graphData);
                }
            }
            return graphData;
        },
        /**
         * 保存下一个节点
         * @param graphData 图数据
         * @param currentList
         * @param parentID
         * @returns
         */
        saveNextNode(graphData, currentList, parentID) {
            for (let index = 0; index < currentList.length; index++) {
                const item = currentList[index];
                console.log("item", item);
                console.log("itemID", item.id);
                const elementProType = item.properties.graphRes_type;
                let recordData = [];
                let sign = '';
                const nextNode = this.$props.lf.getNodeOutgoingNode(item.id);
                console.log("nextNode", nextNode);
                switch (elementProType) {
                    case '对话':
                        sign = signList.get(elementProType);
                        const role = item.properties.roleName;
                        const roleID = item.properties.roleID;
                        const boxPos = item.properties.rolePos ? '右' : '左';
                        const content = item.properties.content;
                        const backPic = item.properties.locationID;
                        let nextID = '';
                        if (nextNode.length > 0) {
                            nextID = nextNode[0].properties.graphRes_id;
                        }
                        recordData = [sign, parentID, item.properties.graphRes_id, role, roleID, boxPos, content, backPic, nextID];
                        graphData.push(recordData);
                        break;
                    case '奖励':
                        const exportReward = this.exportReward(item.properties.rewardList);
                        console.log("exportReward", exportReward);
                        graphData[graphData.length - 1] = graphData[graphData.length - 1].concat(exportReward);
                        console.log("graphData奖励", graphData);
                        break;
                    case '对话流':
                        let convFlowList = item.properties.convFlowList;
                        for (let index = 0; index < convFlowList.length; index++) {
                            sign = '#';
                            const role = item.properties.roleName;
                            const roleID = item.properties.roleID;
                            const boxPos = item.properties.rolePos ? '右' : '左';
                            const backPic = item.properties.locationID;
                            if (index === convFlowList.length - 1) {
                                let convflow = convFlowList[index];
                                const content = convflow.convFlow_content;
                                let nextID = '';
                                if (nextNode.length > 0) {
                                    nextID = nextNode[0].properties.graphRes_id;
                                }
                                recordData = [sign, parentID, convFlowList[index].convFlow_id, role, roleID, boxPos, content, backPic, nextID];
                                graphData.push(recordData);
                            }
                            else {
                                let convflow = convFlowList[index];
                                const content = convflow.convFlow_content;
                                recordData = [sign, parentID, convFlowList[index].convFlow_id, role, roleID, boxPos, content, backPic, convFlowList[index + 1].convFlow_id];
                                graphData.push(recordData);
                            }
                        }
                        break;
                    case '选择':
                        let choiceList = item.properties.choiceList;
                        sign = signList.get(elementProType);
                        for (let index = 0; index < choiceList.length; index++) {
                            let choice = choiceList[index];
                            const content = choice.choice_content;
                            sign = signList.get(elementProType);
                            recordData = [sign, parentID, choiceList[index].choice_id, '', '', '', content, '', choiceList[index].choice_target_id];
                            graphData.push(recordData);
                        }
                        break;
                    case '战斗':
                        sign = signList.get(elementProType);
                        let allFight = '';
                        let nextFightID = '';
                        let nextFightFailID = '';
                        const fightList = item.properties.fightList;
                        for (let index = 0; index < fightList.length; index++) {
                            const fight = fightList[index];
                            const fight_content = fight.fight_id;
                            if (index == 0) {
                                allFight = fight_content;
                            }
                            else {
                                allFight = allFight + '&' + fight_content;
                            }
                        }
                        recordData = [sign, parentID, item.properties.graphRes_id, '', '', '', allFight, '', item.properties.winSkipID, item.properties.failSkipID];
                        graphData.push(recordData);
                        break;
                    case '结束':
                        sign = signList.get(elementProType);
                        const end_content = item.properties.end_content;
                        recordData = [sign, parentID, item.properties.graphRes_id, '', '', '', end_content, '', ''];
                        graphData.push(recordData);
                        break;
                }
                if (nextNode.length > 0) {
                    this.saveNextNode(graphData, nextNode, parentID);
                }
            }
            return graphData;
        },
        exportReward(userReward) {
            const new_array = Array(allRewardData.length).fill('');
            for (const reward of userReward) {
                for (const [index, item] of allRewardData.entries()) {
                    if (reward.reward_name === item.reward_name) {
                        new_array[index] = reward.reward_value;
                    }
                }
            }
            return new_array;
        },
        exportToExcel(exportUrl, saveData) {
            const nodes = this.$props.lf.getGraphData().nodes;
            allRewardData = saveData.allReward;
            // 要导出的数据
            const plotData = this.savePlotCraft(nodes, saveData.allReward);
            const roleData = this.saveRole(saveData.allRole);
            const locationData = this.saveLocation(saveData.allLocation);
            const rewardData = this.saveReward(saveData.allReward);
            // 创建一个新的工作簿
            const workbook = XLSX.utils.book_new();
            // 创建一个工作表
            const worksheet = XLSX.utils.aoa_to_sheet(plotData);
            const worksheet1 = XLSX.utils.aoa_to_sheet(roleData);
            const worksheet2 = XLSX.utils.aoa_to_sheet(locationData);
            const worksheet3 = XLSX.utils.aoa_to_sheet(rewardData);
            // 将工作表添加到工作簿
            XLSX.utils.book_append_sheet(workbook, worksheet, "剧情表"); // 第一个工作簿
            XLSX.utils.book_append_sheet(workbook, worksheet1, "角色表"); // 第一个工作簿
            XLSX.utils.book_append_sheet(workbook, worksheet2, "地点表"); // 第二个工作簿
            XLSX.utils.book_append_sheet(workbook, worksheet3, "奖励表"); // 第二个工作簿
            // 使用promisify来将回调函数转换为Promise
            const writeFileAsync = util_1.default.promisify(fs.writeFile);
            (() => __awaiter(this, void 0, void 0, function* () {
                try {
                    yield writeFileAsync(exportUrl, XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' }));
                    console.log("文件已成功保存到 " + exportUrl);
                    element_plus_1.ElMessage.info("文件已成功保存到 " + exportUrl);
                }
                catch (err) {
                    console.error("保存文件时出错: ", err);
                }
            }))();
        }
    },
    data() {
        return {
            savePath: '',
            selectElement: '',
            undoDisable: true,
            redoDisable: true,
            graphData: null,
            dataVisible: false,
            import_visible: (0, vue_1.ref)(false),
            export_visible: (0, vue_1.ref)(false),
            uuid: ""
        };
    },
    watch: {
        userData: function (newVal, oldVal) {
            this.exportToExcel(this.savePath, newVal);
        }
    },
    created() { },
    computed: {
        isSelectElement() {
            const select = this.$props.lf.getSelectElements(false);
            const selectNode = select.nodes;
            if (selectNode) {
                if (selectNode.length == 0) {
                    this.$data.selectElement = '';
                    return false;
                }
                else {
                    this.$data.selectElement = selectNode;
                    return true;
                }
            }
        },
    },
    mounted() {
        lib_css_1.default.load([
            {
                parent: this.$el,
                url_s: path_1.default.join(`${__dirname}/control_panel.css`),
            },
        ]);
        this.$props.lf.on('history:change', ({ data: { undoAble, redoAble } }) => {
            this.$data.undoDisable = !undoAble;
            this.$data.redoDisable = !redoAble;
        });
    },
};
module.exports = component;
